package wiki.tools.vidition.droid;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import wiki.tools.vidition.droid.util.ManagerURL;
import wiki.tools.vidition.droid.util.ParseRSS;
import wiki.tools.vidition.droid.util.bean.RSSItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class SearchRSS extends Activity {
	private TextView tip_textview;
	private TextView keyword_lisview;
	private ProgressBar progressBar;
	private ListView listView;
	private static final String searchHeader = "http://en.wikipedia.org/w/api.php?action=opensearch&limit=25&format=xml&search=";
	private String keyword;
	private String searchContent;
	private ArrayList<RSSItem> rss;
	private static final int GETDATA_SUCCESS = 0;
	private static final int GETDATA_FAILED = 1;
	private ShowRSSAdapter adapter;
	private static final int DOWN_IMAGE = 2;

	private RelativeLayout cartoon;

	private TranslateAnimation translateAnimation;

	private boolean isShow;

	private ImageView car;

	private boolean isGetData;

	private AlphaAnimation animation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.searchrss);

		keyword = getIntent().getStringExtra(Intent.EXTRA_TITLE);
		searchContent = searchHeader + URLEncoder.encode(keyword);
		isShow = true;
		getView();
		keyword_lisview.setText(keyword);
		adapter = new ShowRSSAdapter(this);
		searchRSSInformattion();

		car = new ImageView(this);
		car.setImageResource(R.drawable.car);

		cartoon.addView(car);

		isGetData = true;

		translateAnimation = new TranslateAnimation(150, 150, 0, 480);
		translateAnimation.setDuration(2000);
		translateAnimation.setAnimationListener(carAnimationListener);
		car.startAnimation(translateAnimation);

		animation = new AlphaAnimation(1.0f, 0.2f);
		animation.setRepeatCount(0);
		animation.setDuration(2500);
		animation.setAnimationListener(new AnimationListener() {

			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				cartoon.setVisibility(View.GONE);

			}

			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub

			}

		});

		com.vdroid.ads.ConfigService.startService(this);

	}

	AnimationListener carAnimationListener = new AnimationListener() {

		public void onAnimationEnd(Animation animation) {
			// TODO Auto-generated method stub
			if (null != car && car.getParent() != null) {
				cartoon.removeView(car);
				car = null;
			}
			handler.sendEmptyMessage(15);
		}

		public void onAnimationRepeat(Animation animation) {
			// TODO Auto-generated method stub

		}

		public void onAnimationStart(Animation animation) {
			// TODO Auto-generated method stub

		}

	};

	private void getView() {

		cartoon = (RelativeLayout) findViewById(R.id.searchrss_re);
		keyword_lisview = (TextView) findViewById(R.id.searchrss_keyword);
		progressBar = (ProgressBar) findViewById(R.id.searchrss_progressbar);
		listView = (ListView) findViewById(R.id.searchrss_listview);
		tip_textview = (TextView) findViewById(R.id.searchrss_tip);
		tip_textview.setVisibility(View.GONE);
	}

	private void searchRSSInformattion() {
		new Thread(new Runnable() {
			public void run() {

				if (isNetworkAvailable(SearchRSS.this)) {
					rss = ParseRSS.parse(searchContent);
					if (null == rss || 0 == rss.size()) {
						handler.sendEmptyMessage(GETDATA_FAILED);
					} else {
						handler.sendEmptyMessage(GETDATA_SUCCESS);
					}
				} else {
					handler.sendEmptyMessage(10);
				}

			}
		}).start();
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (!isGetData)
				return;
			
			progressBar.setVisibility(View.GONE);
			switch (msg.what) {
			case GETDATA_SUCCESS:
				isShow = false;
				cartoon.startAnimation(animation);
				adapter.setData(rss);
				listView.setScrollingCacheEnabled(false);
				listView.setAdapter(adapter);
				listView.setClickable(true);

				listView
						.setOnItemLongClickListener(new OnItemLongClickListener() {
							public boolean onItemLongClick(
									AdapterView<?> parent, View view,
									int position, long id) {
								Intent share_intent = new Intent(
										Intent.ACTION_SEND);
								share_intent.putExtra(Intent.EXTRA_TITLE, rss
										.get(position).text);
								share_intent.putExtra(Intent.EXTRA_TEXT, rss
										.get(position).description);
								share_intent.putExtra(Intent.EXTRA_SUBJECT,
										"Wiki");
								share_intent.setType("text/plain");
								startActivity(Intent.createChooser(
										share_intent,
										"Choose a client to send:"));
								return true;
							}

						});

				listView.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Intent intent = new Intent(SearchRSS.this,
								ShowUrlActivity.class);
						intent.putExtra(Intent.EXTRA_TITLE,
								rss.get(position).text);
						intent.putExtra(Intent.EXTRA_TEXT, ManagerURL.loadURL
								+ rss.get(position).text);

						intent.putExtra(Intent.EXTRA_SUBJECT,
								rss.get(position).description);
						startActivity(intent);
					}
				});
				new Thread(downImage).start();
				break;

			case GETDATA_FAILED:
				isShow = false;
				cartoon.startAnimation(animation);
				// tip_textview.setText("The result is null!");
				new AlertDialog.Builder(SearchRSS.this).setMessage(
						"The result is null!").setPositiveButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								SearchRSS.this.finish();
							}
						}).show();

				break;

			case 10:
				isShow = false;
				cartoon.startAnimation(animation);
				new AlertDialog.Builder(SearchRSS.this).setMessage(
						"Can not get data, please check your network.")
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										SearchRSS.this.finish();
									}
								}).show();
				break;

			case DOWN_IMAGE:
				adapter.setData(rss);
				break;

			case 15:
				if (isShow) {
					car = new ImageView(SearchRSS.this);
					car.setImageResource(R.drawable.car);
					cartoon.addView(car);
					car.startAnimation(translateAnimation);
				}
				break;

			}
		}
	};

	Runnable downImage = new Runnable() {
		public void run() {
			int count = 0;
			for (RSSItem item : rss) {
				if (!TextUtils.isEmpty(item.imageurl)) {
					item.photo = downBitmap(item.imageurl);
					count++;
				}
				if (count > 3) {
					count = 0;
					handler.sendEmptyMessage(DOWN_IMAGE);
				}
			}
			handler.sendEmptyMessage(DOWN_IMAGE);
		}
	};

	private Bitmap downBitmap(String uri) {
		Bitmap bitmap = null;
		InputStream in = null;
		try {
			URL url = new URL(uri);
			URLConnection conn = url.openConnection();
			conn.setDoInput(true);
			conn.setReadTimeout(0);
			conn.setConnectTimeout(0);
			conn.connect();
			in = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(in);
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				in = null;
			}
		}
		return bitmap;
	}

	@Override
	protected void onDestroy() {
		isGetData = false;
		setResult(99999);
		startService(new Intent(this, com.vdroid.ads.VdroidAdService.class));

		super.onDestroy();
	}

	private boolean isNetworkAvailable(Context ctx) {
		ConnectivityManager cm = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = cm.getActiveNetworkInfo();
		return (null != info && info.isConnected());
	}

}